package com.dianrui.agent.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.CoordinatorLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.PolygonOptions;
import com.amap.api.maps.model.PolylineOptions;
import com.dianrui.agent.R;
import com.dianrui.agent.okhttp.OkHttpRequest;
import com.dianrui.agent.util.SharedUtil;
import com.dianrui.agent.util.StringUtils;
import com.dianrui.agent.util.ToastUtil;
import com.dianrui.agent.util.Url;
import com.google.gson.JsonObject;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class TrackPlanningActivity extends BaseActivity {

    private Marker clickMaker;
    private String dispatch_id;
    private String create_time;
    private String end_times;
    private String number;
    private String start_address;
    private double start_longitude;
    private double start_latitude;
    private String end_address;
    private double end_longitude;
    private double end_latitude;
    private List<LatLng> gps = new ArrayList<>();
    private AMap aMap;
    private List<LatLng> mAreaPoints = new ArrayList<>();

    @BindView(R.id.mCoordinatorLayout)
    CoordinatorLayout mCoordinatorLayout;
    @BindView(R.id.mAppBarLayout)
    AppBarLayout mAppBarLayout;
    @BindView(R.id.abnormal_situation)
    TextView abnormalSituation;
    @BindView(R.id.settling_time)
    TextView settlingTime;
    @BindView(R.id.distance)
    TextView distance;
    @BindView(R.id.start_address)
    TextView startAddress;
    @BindView(R.id.end_address)
    TextView endAddress;
    @BindView(R.id.start_times)
    TextView startTimes;
    @BindView(R.id.end_times)
    TextView endTimes;
    @BindView(R.id.track_pullup)
    ImageView trackPullup;
    @BindView(R.id.track_pulldown)
    ImageView trackPulldown;

    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.map)
    MapView map;

    @Override
    public int getContentViewId() {
        return R.layout.activty_planningdetails;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        map.onCreate(savedInstanceState);
    }

    @Override
    public void initView() {
        if (aMap == null) {
            aMap = map.getMap();
        }
        if (getIntent() != null && getIntent().getExtras() != null) {
            Bundle bundle = getIntent().getExtras();
            dispatch_id = bundle.getString("dispatch_id");
        }
        title.setText("调度详情");

        UiSettings mUiSettings = aMap.getUiSettings();
        mUiSettings.setTiltGesturesEnabled(false);
        mUiSettings.setRotateGesturesEnabled(false);
        mUiSettings.setZoomControlsEnabled(false);
        getArea();
        getDispatch();
        loadCoordinatorListener();

        aMap.setOnMarkerClickListener(markerClickListener);
        aMap.setInfoWindowAdapter(infoWindowAdapter);
        aMap.setOnInfoWindowClickListener(listener);
        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                if (clickMaker != null && clickMaker.isInfoWindowShown()) {
                    clickMaker.hideInfoWindow();
                }
            }
        });

    }

    private void getDispatch() {
        JsonObject jsonObject = new JsonObject();
        jsonObject.addProperty("dispatch_id", dispatch_id);
        OkHttpRequest.getInstance().postTokenRequests(SharedUtil.getUrl()+Url.DISPATCHDETAIL, jsonObject.toString(), new OkHttpRequest.XCallBack() {
            @Override
            public void onResponse(String result) {
                if (!StringUtils.isEmpty(result)) {
                    try {
                        JSONObject jsonObject = new JSONObject(result);
                        if (jsonObject != null) {
                            if ("1000".equals(jsonObject.optString("status"))) {
                                if (null != gps && gps.size()>0) {
                                    gps.clear();
                                }

                                abnormalSituation.setText(jsonObject.optJSONObject("data").optString("abnormal_situation"));
                                startTimes.setText(jsonObject.optJSONObject("data").optString("create_time"));
                                endTimes.setText(jsonObject.optJSONObject("data").optString("end_time"));
                                settlingTime.setText(jsonObject.optJSONObject("data").optString("settling_time"));
                                distance.setText(jsonObject.optJSONObject("data").optString("distance")+"米");
                                startAddress.setText(jsonObject.optJSONObject("data").optString("start_address"));
                                endAddress.setText(jsonObject.optJSONObject("data").optString("end_address"));

                                final JSONArray jsonArray = jsonObject.optJSONObject("data").optJSONArray("gps");
                                if (jsonArray.length() > 0) {
                                    LatLng current = new LatLng(jsonArray.optJSONObject(jsonArray.length() - 1).optDouble("glat"), jsonArray.optJSONObject(jsonArray.length() - 1).optDouble("glng"));
                                    aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(current,15));
                                    for (int i = 0; i < jsonArray.length(); i++) {
                                        gps.add(new LatLng(jsonArray.optJSONObject(i).optDouble("glat"), jsonArray.optJSONObject(i).getDouble("glng")));
                                    }
                                    if (jsonArray.length() > 1) {
                                        View startPointView = LayoutInflater.from(TrackPlanningActivity.this).inflate(R.layout.start_point, null);
                                        Marker marker = aMap.addMarker(new MarkerOptions().position(new LatLng( jsonArray.optJSONObject(jsonArray.length() - 1).optDouble("glat"), jsonArray.optJSONObject(jsonArray.length() - 1).optDouble("glng"))).icon(BitmapDescriptorFactory.fromView(startPointView)).zIndex(99));
                                        marker.setObject(jsonObject.optJSONObject("data").optString("start_address"));
                                        marker.setSnippet("start_address");

                                        View endPointView = LayoutInflater.from(TrackPlanningActivity.this).inflate(R.layout.end_point, null);
                                        Marker marker1 = aMap.addMarker(new MarkerOptions().position(new LatLng( jsonArray.optJSONObject(0).optDouble("glat"), jsonArray.optJSONObject(0).getDouble("glng"))).icon(BitmapDescriptorFactory.fromView(endPointView)).zIndex(100));
                                        marker1.setObject(jsonObject.optJSONObject("data").optString("end_address"));
                                        marker1.setSnippet("end_address");

                                    }else {
                                        View endPointView = LayoutInflater.from(TrackPlanningActivity.this).inflate(R.layout.end_point, null);
                                        Marker marker1 = aMap.addMarker(new MarkerOptions().position(new LatLng( jsonArray.optJSONObject(0).optDouble("glat"), jsonArray.optJSONObject(0).getDouble("glng"))).icon(BitmapDescriptorFactory.fromView(endPointView)).zIndex(100));
                                        marker1.setObject(jsonObject.optJSONObject("data").optString("end_address"));
                                        marker1.setSnippet("end_address");
                                    }
                                }

                                if (gps.size()>1){
                                    List<BitmapDescriptor> textureList = new ArrayList<>();
                                    textureList.add(BitmapDescriptorFactory.fromResource(R.mipmap.customer_img));

                                    List<Integer> textureIndexs = new ArrayList<>();
                                    textureIndexs.add(0);
                                    aMap.addPolyline(new PolylineOptions().addAll(gps).width(4).setCustomTextureList(textureList).setCustomTextureIndex(textureIndexs).setDottedLine(true));
                                }

                            }else if ("1001".equals(jsonObject.optString("status"))) {
                                ToastUtil.showToast(jsonObject.optString("message"));
                            } else if ("1002".equals(jsonObject.optString("status"))) {
                                spUtils.clear();
                                ToastUtil.showToast(jsonObject.optString("message"));
                                JumpActivitys(LoginActivity.class);
                                finish();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void FailedRequest(String result) {
                ToastUtil.showToast(getString(R.string.net_error));
            }
        });
    }

    //监听Coordinator滑动
    private void loadCoordinatorListener() {
        try {
            CoordinatorLayout.Behavior behavior = ((CoordinatorLayout.LayoutParams) mAppBarLayout.getLayoutParams()).getBehavior();
            if (behavior instanceof BottomSheetBehavior) {
                BottomSheetBehavior myBehavior = (BottomSheetBehavior) behavior;
                myBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
                    @Override
                    public void onStateChanged(@NonNull View bottomSheet, int newState) {
                        if (newState == 3) {//手拉到顶部值的是3
                            trackPulldown.setVisibility(View.VISIBLE);
                            trackPullup.setVisibility(View.GONE);
                        }
                    }

                    @Override
                    public void onSlide(@NonNull View bottomSheet, float slideOffset) {
                        if (slideOffset == 0.0f) {//手拉到底部是0.0
                            trackPulldown.setVisibility(View.GONE);
                            trackPullup.setVisibility(View.VISIBLE);
                        }
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    private void getArea() {
        if (!StringUtils.isEmpty(spUtils.getString("area"))) {
            try {
                final JSONObject jsonObject = new JSONObject(spUtils.getString("area"));
                if (jsonObject != null) {
                    if (mAreaPoints != null) {
                        mAreaPoints.clear();
                    }
                    JSONArray gfixed_path = jsonObject.optJSONObject("data").optJSONArray("fixed_path");
                    if (gfixed_path.length() > 0) {
                        for (int j = 0; j < gfixed_path.length(); j++) {
                            JSONObject jsonObject3 = gfixed_path.optJSONObject(j);
                            mAreaPoints.add(new LatLng(jsonObject3.optDouble("lat"), jsonObject3.optDouble("lng")));
                        }

                        if (mAreaPoints.size() > 0) {
                            PolygonOptions polygonOptions = new PolygonOptions();
                            polygonOptions.addAll(mAreaPoints);
                            polygonOptions.strokeWidth(6);
                            polygonOptions.strokeColor(Color.rgb(255, 0, 0));
                            polygonOptions.fillColor(Color.argb(0, 0, 0, 0));
                            aMap.addPolygon(polygonOptions);
                        }

                    }

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }


    // 定义 Marker 点击事件监听
    AMap.OnMarkerClickListener markerClickListener = new AMap.OnMarkerClickListener() {
        @Override
        public boolean onMarkerClick(final Marker marker) {
            clickMaker = marker;
            marker.showInfoWindow();
            return true;
        }
    };

    AMap.InfoWindowAdapter infoWindowAdapter = new AMap.InfoWindowAdapter() {
        @Override
        public View getInfoWindow(Marker marker) {
            if (marker.getSnippet().equals("start_address")) {
                View view = LayoutInflater.from(TrackPlanningActivity.this).inflate(R.layout.show_planning_bubble, null);
                TextView address = view.findViewById(R.id.address);
                address.setText(marker.getObject().toString());
                return view;
            }else {
                View view = LayoutInflater.from(TrackPlanningActivity.this).inflate(R.layout.show_planning_bubble, null);
                TextView address = view.findViewById(R.id.address);
                address.setText(marker.getObject().toString());
                return view;
            }
        }

        @Override
        public View getInfoContents(Marker marker) {
            return null;
        }
    };

    //点击marker就消失
    AMap.OnInfoWindowClickListener listener = new AMap.OnInfoWindowClickListener() {
        @Override
        public void onInfoWindowClick(Marker marker) {
            marker.hideInfoWindow();
        }
    };


    @Override
    protected void onResume() {
        super.onResume();
        map.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        map.onPause();
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        map.onSaveInstanceState(outState);
    }


    @OnClick(R.id.back)
    public void onViewClicked() {
        finish();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        map.onDestroy();
        if (gps != null) {
            gps.clear();
        }

        if (mAreaPoints != null) {
            mAreaPoints.clear();
        }
    }
}
